package com.sx.controller;

import com.sx.pojo.Person;
import com.sx.pojo.SaleBill;
import com.sx.service.GoodService;
import com.sx.service.PersonService;
import com.sx.service.SaleBillService;
import com.sx.service.serviceImpl.GoodServiceImpl;
import com.sx.service.serviceImpl.PersonServiceImpl;
import com.sx.service.serviceImpl.SaleBillServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serial;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/saleBill.action")
public class SaleBillServlet extends HttpServlet {
    @Serial
    private static final long serialVersionUID = 1L;
    private final SaleBillService saleBillService = new SaleBillServiceImpl();
    private final GoodService goodService = new GoodServiceImpl();
    private final PersonService personService = new PersonServiceImpl();
    private final Logger logger = LogManager.getLogger(SaleBillServlet.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String action = req.getParameter("action");
        //获取session
        HttpSession session = req.getSession();
        Person user = null;
        if (session.getAttribute("person") == null) {
            // 重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/login");
            return;
        } else {
            user = (Person) session.getAttribute("person");
        }
        switch (action) {
            case "list" -> {
                ArrayList<SaleBill> saleBills = saleBillService.getAllSaleBill();
                req.setAttribute("saleBillList", saleBills);
                req.setAttribute("mainRight", "/jsp/saleBillList.jsp");
                // 转发请求到index.jsp页面
                req.getRequestDispatcher("/jsp/index.jsp").forward(req, resp);
            }
            case "add" -> {
                req.setAttribute("goodsList", goodService.getAllGoods());
                req.setAttribute("personList", personService.getAllPerson());
                // 设置mainRight属性，指定右侧主要内容页面
                req.setAttribute("mainRight", "/jsp/addSaleBill.jsp");
                // 转发请求到index.jsp页面
                req.getRequestDispatcher("/jsp/index.jsp").forward(req, resp);
            }
            case "delete" -> {
                //  删除信息操作
                // 设置响应内容类型为 JSON
                String id = req.getParameter("id");
                resp.setContentType("application/json;charset=UTF-8");
                PrintWriter out = resp.getWriter();
                if (id == null) {
                    out.print("{\"status\":\"error\",\"message\":\"删除失败，请选择要删除的数据。\"}");
                } else {
                    try {
                        // 这里假设你会调用相应的服务层方法进行人员删除操作
                        // 例如：PersonService.deletePerson(id);
                        // 这里为了示例，模拟删除操作成功或失败
                       // boolean success = saleBillService.deleteSaleBillById(id);
                        boolean success = saleBillService.deleteSaleBillById(user.getId(), user.getName(),3,5,id);
                        if (success) {
                            // 删除成功，返回成功信息
                            out.print("{\"status\":\"success\",\"message\":\"删除成功\"}");
                            // resp.sendRedirect("/person.action?action=list");
                        } else {
                            // 删除失败，返回失败信息和原因
                            out.print("{\"status\":\"error\",\"message\":\"删除失败，可能是因为关联数据存在，请先处理关联数据。\"}");
                        }
                    } catch (Exception e) {
                        // 异常处理，返回错误信息
                        out.print("{\"status\":\"error\",\"message\":\"删除操作发生异常，请稍后重试。\"}");
                    }

                }
            }
            case "update" -> {
                try {
                    String saleBillID = req.getParameter("id");
                    SaleBill saleBill = saleBillService.getSaleBillById(saleBillID);
                    req.setAttribute("saleBill", saleBill);
                    req.setAttribute("goodsList", goodService.getAllGoods());
                    req.setAttribute("personList", personService.getAllPerson());
                    req.setAttribute("mainRight", "/jsp/updateSaleBill.jsp");
                    req.getRequestDispatcher("/jsp/index.jsp").forward(req, resp);
                } catch (Exception e) {
                    logger.error(e);
                }
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //当添加销售表时对应的商品数量要减少
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String action = req.getParameter("action");
        //获取session
        HttpSession session = req.getSession();
        Person user = null;
        if (session.getAttribute("person") == null) {
            // 重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/login");
            return;
        } else {
            user = (Person) session.getAttribute("person");
        }
        if (action != null && action.equals("save")) {
            String saleBillID = req.getParameter("saleBillID");
            String goods_id = req.getParameter("goods_id");
            String goods_name = req.getParameter("goods_name");
            String IsSale_Date = req.getParameter("sale_Date");
            Date sale_Date = Date.valueOf(IsSale_Date);
            int number = Integer.parseInt(req.getParameter("number"));
            int person_id = Integer.parseInt(req.getParameter("person_id"));
            String person_name = req.getParameter("person_name");
            int i;
                i = saleBillService.saveSaleBill(new SaleBill(saleBillID, goods_id, goods_name, sale_Date, number, person_id, person_name),user.getId(),user.getName(),1,5);
            if (i==1) {
                logger.info("添加成功");
                resp.getWriter().write("添加成功");
            }else if(i==2){
                logger.info("添加失败");
                resp.getWriter().write("添加失败,销售单上的数量大于商品库存");
            }else if(i==3){
                logger.info("添加失败");
                resp.getWriter().write("添加失败");
            }
        } else if (action != null && action.equals("update")) {

            String saleBillID = req.getParameter("saleBillID");
            String goods_id = req.getParameter("goods_id");
            String goods_name = req.getParameter("goods_name");
            String IsSale_Date = req.getParameter("sale_Date");
            Date sale_Date = Date.valueOf(IsSale_Date);
            int number = Integer.parseInt(req.getParameter("number"));
            int person_id = Integer.parseInt(req.getParameter("person_id"));
            String person_name = req.getParameter("person_name");
            boolean flag = saleBillService.updateSaleBill(new SaleBill(saleBillID, goods_id, goods_name, sale_Date, number, person_id, person_name),user.getId(),user.getName(),2,5,saleBillID);
            if (flag) {
                logger.info("修改成功");
                resp.getWriter().write("修改成功");
            } else {
                logger.info("修改失败");
                resp.getWriter().write("修改失败");
            }
        }
    }
}
